package handler

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/remotecommand"
	"net/http"
	"twwch/k8s-admin/apis"
	"twwch/k8s-admin/pkg/terminal/websocket"
)

type PodHandler struct {
}

var Pod = &PodHandler{}

func (h *PodHandler) Shell(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Shell start")
	//pathParams := mux.Vars(r)
	namespace := r.URL.Query().Get("namespace")
	podName := r.URL.Query().Get("pod")
	command := r.URL.Query().Get("command")
	if command == "" {
		command = "sh"
	}
	log.Printf("exec pod: %s,, namespace: %s\n", podName, namespace)
	pty, err := websocket.NewTerminalSession(w, r, nil)
	if err != nil {
		log.Printf("get pty failed: %v\n", err)
		return
	}
	defer func() {
		log.Println("close session.")
		pty.Close()
	}()
	defer func() {
		pty.Done()
	}()

	req := apis.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(podName).
		Namespace(namespace).
		SubResource("exec")

	req.VersionedParams(&corev1.PodExecOptions{
		//Container: containerName,
		Command: []string{fmt.Sprintf("/bin/%v", command)},
		Stdin:   !(pty.Stdin() == nil),
		Stdout:  !(pty.Stdout() == nil),
		Stderr:  !(pty.Stderr() == nil),
		TTY:     pty.Tty(),
	}, scheme.ParameterCodec)

	executor, err := remotecommand.NewSPDYExecutor(apis.Config(), "POST", req.URL())
	if err != nil {
		pty.Write([]byte(err.Error()))
	}
	err = executor.Stream(remotecommand.StreamOptions{
		Stdin:             pty.Stdin(),
		Stdout:            pty.Stdout(),
		Stderr:            pty.Stderr(),
		TerminalSizeQueue: pty,
		Tty:               pty.Tty(),
	})
	if err != nil {
		pty.Write([]byte(err.Error()))
	}
}
